package xyz.heyaoshare.config.web;

import cn.dev33.satoken.interceptor.SaInterceptor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xyz.heyaoshare.config.properties.WebProperties;
import xyz.heyaoshare.interceptor.SQLInjectionInterceptor;

/**
 * Web配置类
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/26 下午4:51
 */
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private WebProperties webProperties;
    @Resource
    private SQLInjectionInterceptor sqlInjectionInterceptor;

    /**
     * 创建一个跨域过滤器，允许所有来源、方法和头部跨域访问。
     *
     * @return 跨域过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedMethod("*");

        // 添加需要暴露的响应头
        corsConfiguration.addExposedHeader("Content-disposition");
        corsConfiguration.addExposedHeader("Authorization");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

    /**
     * 注册 Sa-Token 拦截器，打开注解式鉴权功能
     * @param registry 拦截器注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册防SQL注入拦截器
        registry.addInterceptor(sqlInjectionInterceptor).addPathPatterns("/**");
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**").excludePathPatterns(webProperties.getWhiteList());
    }

    /**
     * 添加资源处理器
     * @param registry 资源处理器注册器
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/openapi.json").addResourceLocations("classpath:/static/");
    }

}
